package com.qifenqian.turbot.util

import android.content.Context
import android.widget.TextView
import com.qifenqian.turbot.R
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * @author H
 * @createTime 2018/12/14 16:35
 * @description 发送验证码的倒计时处理
 * @see
 * @since
 */
object SendSmsUtil {

    private var mCountdownDisposable: Disposable? = null

    /**
     * 开始倒计时
     */
    fun beginCountdown(context: Context, time: Long, tv: TextView) {
        Observable.intervalRange(0, time + 1, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Long> {
                    override fun onSubscribe(d: Disposable) {
                        mCountdownDisposable = d
                        tv.isClickable = false
                    }

                    override fun onNext(aLong: Long) {
                        tv.text = (time - aLong).toString() + "s后重新获取"
                        tv.setTextColor(context.resources.getColor(R.color.gray_666666))
                        tv.isClickable = false

                    }

                    override fun onError(e: Throwable) {
                        tv.text = "重新发送"
                        tv.setTextColor(context.resources.getColor(R.color.gray_666666))
                        tv.isClickable = true
                    }

                    override fun onComplete() {
                        tv.text = "重新发送"
                        tv.setTextColor(context.resources.getColor(R.color.black))
                        tv.isClickable = true
                    }
                })
    }

    /**
     * 发送失败的时候要关闭倒计时
     */
    fun disposeCountdown() {
        if (mCountdownDisposable != null && !mCountdownDisposable!!.isDisposed) {
            mCountdownDisposable!!.dispose()
        }
    }
}